const fs = require("fs");
const path = require("path");
const iconv = require("iconv-lite");
const txtDir = path.join(__dirname, "..", "resources", "grammar");
const mdDir = path.join(__dirname, "..", "resources", "grammar_md");

if (!fs.existsSync(mdDir)) {
  fs.mkdirSync(mdDir);
}

for (const file of fs.readdirSync(txtDir)) {
  const filePath = path.join(txtDir, file);
  const mdFilePath = path.join(mdDir, file.replace(".txt", ".md"));
  let content = fs.readFileSync(filePath);
  const buffer = fs.readFileSync(filePath);
  content = iconv.decode(buffer, "gbk");
  let mdContent = content.replace(/\n/g, "\n  ");
  const lines = mdContent.split("\n");
  let special = false;
  for (let i = 0; i < lines.length; i++) {
    let line = lines[i];
    if (i === 0) {
      line = line.replace(line, `# ${line}`);
      lines[i] = line;

      if(line.indexOf("# 1. 名词")>-1){
        special = true;
        lines[10] = "<pre>  "
        lines[24] = "</pre>  ";
      }

      continue;
    }

    if(special && i >=10) continue;

    // 处理原始文件中选项中被错误换行的
    if (i + 1 < lines.length) {
      if (lines[i + 1].trimStart().indexOf("D.") === 0) {
        if (lines[i].trimStart().indexOf("A.") === 0) {
          lines[i] = lines[i].replaceAll("\n\n", "  ") + lines[i + 1];
          lines[i + 1] = "";
        }
      }
    }

    // 如果以'　'开头，则去掉开头的'　'
    if (line.startsWith("　")) {
      line = line.replaceAll(/　/g, "");
      lines[i] = line;
    }
    const tempLine = line
      .replaceAll(" ", "")
      .replaceAll("　", "")
      .replaceAll("　", "");
    if (lines[0].indexOf("12.4") > 0 && i > 1000) {
      console.log(line);
      console.log("--0--");
      console.log(lines[0]);
      console.log("--1--");
      console.log(lines[i]);
      console.log("--2--");
      console.log(lines[i + 1]);
      console.log("--3--");
      console.log(lines[i + 2]);
      console.log("--4--");
      console.log(lines[i + 3]);
      console.log(
        lines[i + 3]
          .replaceAll(" ", "")
          .replaceAll("　", "")
          .replaceAll("　", "")
      );
      if (
        /^\d+\)/.test(
          lines[i + 3]
            .replaceAll(" ", "")
            .replaceAll("　", "")
            .replaceAll("　", "")
        )
      ) {
        console.log("--OKKKKK-1-");
      }
      if (
        /^\d+）/.test(
          lines[i + 3]
            .replaceAll(" ", "")
            .replaceAll("　", "")
            .replaceAll("　", "")
        )
      ) {
        console.log("--OKKKKK-2-");
      }
      if (
        /^\d+[）\)]/.test(
          lines[i + 3]
            .replaceAll(" ", "")
            .replaceAll("　", "")
            .replaceAll("　", "")
        )
      ) {
        console.log("--OKKKKK-3-");
      }
      console.log("--5--");
      console.log(lines[i + 4]);
      console.log("--over--");
    }
    // 如果以'数字+.'开头，则在前面添加'## '
    // TODO: 待完善
    if (/^\d+\./.test(tempLine)) {
      lines[i] = `## ${line}`;
    }
    if (/^\d+\．/.test(tempLine)) {
      lines[i] = `## ${line}`;
    }
    // 如果以'数字)'或者'数字）' 开头，则开头添加为'- '，并且将'）'替换为')'
    // TODO: 待完善
    if (/^\d+[）\)]/.test(tempLine)) {
      line = line.replaceAll("）", ")");
      lines[i] = `#### ${line.trimStart()}`;
    }

    // 一行去掉空格（' ','　'）后，内容为典型例题，则修改为'#### '+典型例题
    // TODO: 待完善
    if (line.indexOf("典型例题") > -1) {
      lines[i] = "#### 📚*典型例题*";
    }
    if (line.indexOf("判断改错") > -1) {
      lines[i] = "#### 🚥*判断改错*";
    }
    // 如果以字母.开头，则替换为 #### + 该行内容
    if (/^[a-zA-Z]\./.test(line) && line.indexOf("B.") === -1) {
      lines[i] = "#### " + line;
    }
    // 如果是一个汉字数字+、开头，则替换为 ## + 该行内容
    const chNums = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
    for (let j = 0; j < chNums.length; j++) {
      if (line.trimStart().startsWith(chNums[j] + "、")) {
        lines[i] = "## " + line;
        continue;
      }
    }

    if (
      lines[i].trimStart().indexOf("A.") === 0 &&
      lines[i].indexOf("B.") > 0
    ) {
      lines[i] = lines[i].replace("A.", "<input type='checkbox'/>A.");
      lines[i] = lines[i].replace("B.", "<input type='checkbox'/>B.");
      lines[i] = lines[i].replace("C.", "<input type='checkbox'/>C.");
      lines[i] = lines[i].replace("D.", "<input type='checkbox'/>D.");
    }

    lines[i] = lines[i].replaceAll("　　", " ");
    lines[i] = lines[i].replaceAll("：　", ":");

    lines[i] = lines[i].replace(
      "句型：",
      "***<font color=lightdark>🍊句型：</font>***"
    );
    lines[i] = lines[i].replace("说明：", "<font>✋️说明：</font>");
    lines[i] = lines[i].replace("动词", "<font color=lightdark>动词💃</font>");
    lines[i] = lines[i].replace("答案：", "<font color=green>💡答案：</font>");
    lines[i] = lines[i].replace(
      "例如：",
      "<font style='font-style:italic'>🌲例如：</font>"
    );
    if (lines[i].indexOf("举例") === -1)
      lines[i] = lines[i].replace(
        "例：",
        "<font style='font-style:italic;'>🌲例：</font>"
      );
    if (lines[i].indexOf("举例") === -1)
      lines[i] = lines[i].replace(
        "例:",
        "<font style='font-style:italic;'>🌲例:</font>"
      );
    lines[i] = lines[i].replace(
      "举例：",
      "<font style='font-style:italic;'>🌲举例：</font>"
    );
    // 以[‘例’开头加一个数字和点号]的，给[‘例’开头加一个数字和点号]设置下划线样式
    const regex = /例(\d+)\./g;
    // 使用 ANSI 下划线转义序列包裹匹配内容（\x1B[4m 开启下划线，\x1B[0m 关闭）
    lines[i] = lines[i].replace(
      regex,
      '<span style="background-color:lightgreen;">例$1.</span>'
    );
    const regex1 = /说明(\d+)\：/g;
    // 使用 ANSI 下划线转义序列包裹匹配内容（\x1B[4m 开启下划线，\x1B[0m 关闭）
    lines[i] = lines[i].replace(regex1, "✋️说明$1：");
    const regex2 = /比较：/g;
    // 使用 ANSI 下划线转义序列包裹匹配内容（\x1B[4m 开启下划线，\x1B[0m 关闭）
    lines[i] = lines[i].replace(
      regex2,
      '<span style="background-color:yellow;">🆚比较：</span>'
    );
    if (
      lines[i].trimStart().startsWith("答案A。") ||
      lines[i].trimStart().startsWith("答案B。") ||
      lines[i].trimStart().startsWith("答案C。") ||
      lines[i].trimStart().startsWith("答案D。") ||
      lines[i].trimStart().startsWith("答案A.") ||
      lines[i].trimStart().startsWith("答案B.") ||
      lines[i].trimStart().startsWith("答案C.") ||
      lines[i].trimStart().startsWith("答案D.")
    ) {
      lines[i] = `<span style='text-decoration:underline'>👩${lines[
        i
      ].trimStart()}</span>`;
    }

    lines[i] = lines[i].replace("注意:", "<font color=Red>⚠️注意:</font>*");
    lines[i] = lines[i].replace("注意：", "<font color=Red>⚠️注意:</font>*");
    lines[i] = lines[i].replace("表示：", " *表示：*");
    lines[i] = lines[i].replace("（对）", "(对)");
    lines[i] = lines[i].replace("（错）", "(错)");
    lines[i] = lines[i].replace("(对)", "(✅️)");
    lines[i] = lines[i].replace("(错)", "(❌️)");

    const items = ["手表", "中国人", "学生", "马", "老师"];
    const itemsSymbols = ["手表⌚️", "中国人", "学生👩‍🎓", "马🐴", "老师👩‍🏫"];
    for (let j = 0; j < items.length; j++) {
      lines[i] = lines[i].replace(items[j], itemsSymbols[j]);
    }

    lines[i].indexOf("🌲") === -1 &&
      (lines[i] = lines[i].replace("如:", "🌲如:"));
    lines[i].indexOf("🌲") === -1 &&
      (lines[i] = lines[i].replace("如：", "🌲如:"));
    lines[i] = lines[i].trimStart();
    lines[i] = lines[i] + "  ";
  }
  mdContent = lines.join("\n");

  fs.writeFileSync(mdFilePath, mdContent, { encoding: "utf8" });
}
